/* eslint-disable no-undef */
// import { getFile, GET_FILE_URL } from '@/api/file';
// import getConfig from '@/server/getConfig';
// import axios from 'axios';
// import { getFileList, uploadFileMulti } from '@/api/formview';

// todo 请求文件列表
/*
  data: {
    type: string;
    appId: string;
  }
*/

const conversionBase64 = (blob) => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    return new Promise(resolve => {
        reader.onload = ({ target: { result } }) => {
            resolve(result);
        };
    });
};

// const saveFileToLocal = (blob, fileName) => {
//   const a = document.createElement('a');
//   const url = window.URL.createObjectURL(blob);
//   const filename = fileName;
//   a.href = url;
//   a.download = filename;
//   a.click();
//   window.URL.revokeObjectURL(url);
//   a.remove();
// };

// todo 下载文件
/*
  data: {
    id: string
    fileName: string
    originName: string
  }

  type: string // pic | file ;   //type === pic 返回base64 否则直接下载打开
*/
// const downFile = async(data, type) => {
//   const { data: blob } = await getFile({
//     id: data.id,
//     fileName: data.saveName
//   });
//   if (type === 'pic') {
//     return await conversionBase64(blob);
//   } else {
//     saveFileToLocal(blob, data.saveName);
//   }
// };

// const fileView = async function fileView(id) {
//   const { data: { ApiUrl }} = await getConfig();
//   const fileViewUrl = `${
//     ApiUrl
//   }onlinePreview?fileId=${id}`;

//   window.open(fileViewUrl);
// };

// const downFileServer = url => {
//   return axios.get(url, {
//     responseType: 'blob'
//   });
// };

const dataURLtoFile = function(dataUrl, filename) {
    const arr = dataUrl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
};

// const getListFiles = function(data, headers = {}) {
//   return getFileList(data, headers);
// };

// const upFileMulti = function(data) {
//   return uploadFileMulti(data);
// };

// 选择图片
const chooseImgs = function() {
    return new Promise((r, j) => {
        uni.chooseImage({
            count: 9,
            success: (res) => {
                r({
                    paths: res.tempFilePaths,
                    files: res.tempFiles
                });
            },

            fail: () => {
                j('调用图片失败');
            }
        });
    });
};

// 选择附件
const chooseFile = function() {
    return new Promise((r, j) => {
        uni.chooseImage({
            count: 1,
            success: (res) => {
                r({
                    paths: res.tempFilePaths,
                    files: res.tempFiles
                });
            },

            fail: () => {
                j('上传附件失败');
            }
        });
    });
};

// h5
const getH5Base64ImageByUrl = (url) => {
    const img = new Image()
    //解决跨域问题
    img.setAttribute("crossOrigin", 'anonymous');
    //如果需要兼容ios，这两个顺序一定不能换，先设置crossOrigin后设置src
    img.src = url;
    return new Promise((resolve, reject) => {
        img.onload = () => {
            const canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;
            const ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            resolve({
                success: true,
                //canvas.toDataURL的方法将图片的绝对路径转换为base64编码
                base64: canvas.toDataURL().split(',')[1]
            })
        }
        img.onerror = () => {
            reject({ success: false })
        }
    })
}

const getWeChatBase64ImageByUrl = function(url) {
    return new Promise((r, j) => {
        wx.getFileSystemManager().readFile({
            filePath: url, //选择图片返回的相对路径
            encoding: 'base64', //编码格式
            success: ({ data }) => {
                r({
                    success: true,
                    base64: data
                    // base64: 'data:image/jpg;base64,' + data
                })
            },
            fail: () => {
                j({
                    success: false
                })
            }
        });

    })
}

const getAliPayBase64ImageByUrl = function(imagePath, self) {
    // 支付宝需要手动添加 
    /* 
    imgWidth: 0, imgHeight: 0
    <canvas
      v-show="false"
      :width="imgWidth"
      :height="imgHeight"
      style="opacity: 0; position: absolute;pointer-events: none;"
      id="canvasForBase64"
    />
    */

    return new Promise((resolve, reject) => {
        my.getImageInfo({
            src: imagePath,
            success: async (res) => {
                const { width, height } = res;
                self.imgWidth = width;
                self.imgHeight = height;
                let canvas = my.createCanvasContext("canvasForBase64");
                canvas.drawImage(imagePath, 0, 0, width, height); // 1. 绘制图片至canvas
                // 绘制完成后执行回调
                canvas.draw(false, async () => {
                    let base64 = await canvas.toDataURL({
                        width,
                        height,
                        quality: 1,
                    });
                    resolve({
                        success: true,
                        base64
                    })

                    // base64 = base64.replace("data:image/png;base64,", "");
                    // await this.uploadImageRequest(base64);
                });
            },
        });
    })
}



const getBase64ImageByUrl = function(url, self) {
    // #ifdef MP-WEIXIN
    return getWeChatBase64ImageByUrl(url)
    // #endif

    // #ifdef MP-ALIPAY
    return getAliPayBase64ImageByUrl(url, self);

    // #endif

    // #ifdef H5
    return getH5Base64ImageByUrl(url);
    // #endif
}


export {
    // downFile,
    // fileView,
    // downFileServer,
    dataURLtoFile,
    conversionBase64,
    // getListFiles,
    // upFileMulti,
    chooseImgs,
    chooseFile,
    getBase64ImageByUrl,
    // GET_FILE_URL
};